package com.zhouyu.fileSync.FSclient.transmission.communicationBetweenClients.server;

import com.zhouyu.fileSync.FSclient.ClientAppContext;
import com.zhouyu.fileSync.FScommon.api.JSONDecoder;
import com.zhouyu.fileSync.FScommon.api.JSONEncoder;
import com.zhouyu.fileSync.FScommon.commonUtils.ServerMapUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * transmission server
 * receive the transmission job request
 */
public class CommunicationServer implements Runnable{

    Logger logger = LogManager.getLogger(CommunicationServer.class);
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup();


    @Override
    public void run() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //创建NIOSocketChannel成功后，在进行初始化时，将它的ChannelHandler设置到ChannelPipeline中，用于处理网络IO事件
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new IdleStateHandler(0, 0, 60));
                            pipeline.addLast(new DelimiterBasedFrameDecoder(65535, Unpooled.copiedBuffer("#_@_#".getBytes())));
                            pipeline.addLast(new JSONEncoder());
                            pipeline.addLast(new JSONDecoder());
                            pipeline.addLast(new CommunicationServerHandler(ServerMapUtils.getServiceMap("com.zhouyu.fileSync.FSclient")));
                        }
                    });
            int port = ClientAppContext.CONFIGS.CLIENT.getClientPort();
            ChannelFuture cf = bootstrap.bind(port).sync();
            logger.info("client rpc server node start up! bind port:" + port);
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
